package com.its.cloud.service.impl;

import com.its.cloud.dao.OrderMapper;
import com.its.cloud.entity.Order;
import com.its.cloud.service.AccountService;
import com.its.cloud.service.OrderService;
import com.its.cloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author huguangjun
 * @className OrderServiceImpl
 * @date 2021/1/17
 * @desc 16:36
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    /**
     * 下方是微服务调用
     */
    @Resource
    private AccountService accountService;
    @Resource
    private StorageService storageService;

    /**
     * 下单
     * 测试 seata 分布式事务
     *
     * @param order
     */
    @Override
    // seata的分布式事务控制，name任意起名但要唯一，捕获的行为所有异常回滚
    @GlobalTransactional(name = "tx_fsp_create_order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.error("---------------------------------->下订单开始了-end");
        orderMapper.create(order);

        log.error("-------->订单微服务开始调用库存，做扣减count-start");
        storageService.decrease(order.getProductId(), order.getCount());
        log.error("-------->订单微服务开始调用库存，做扣减count-end");

        log.error("-------->订单微服务开始调用账户，做扣减money-start");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.error("-------->订单微服务开始调用账户，做扣减money-end");

        log.error("-------->修改订单状态-start");
        orderMapper.update(order.getUserId(), 0);
        log.error("-------->修改订单状态-end");

        log.error("---------------------------------->下订单结束了-end");
    }
}
